using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Text;
using System.Diagnostics;

namespace GoodStuff
{
    public class ThreadSafeQueue<T>
    {
        Queue _queue;
        Queue Queue                                                             // gets the (not thread safe) queue
        {
            get { return _queue; }
        }

        AutoResetEvent _event;                                                  // event triggers on call to enqueue
        AutoResetEvent Event
        {
            get { return _event; }
        }
        public ThreadSafeQueue(int capacity)
        {
            Trace.WriteLine("ThreadSafeQueue constructor called");
            _queue = new Queue(capacity);
            _event = new AutoResetEvent(false);
        }
        public int Count
        {
            get
            {
                int c;
                lock (_queue.SyncRoot)
                {
                    c = _queue.Count;
                }
                return c;
            }
        }
        public void Enqueue(T o)
        {
            lock(_queue.SyncRoot)
            {
                _queue.Enqueue(o);
            }
            _event.Set();
        }
        public T Dequeue()
        {
            T o;
            lock (_queue.SyncRoot)
            {
                o = (T)_queue.Dequeue();
            }
            Trace.Assert(o != null, "Big error -- wrong type of object in ThreadSafeQueue");
            return o;
        }
        public void Wait()
        {
            _event.WaitOne();
        }
        public bool Wait(int timeout)
        {
            return _event.WaitOne(timeout, false);
        }
        public void Clear()
        {
            lock (_queue.SyncRoot)
            {
                _queue.Clear();
            }
        }
    }
}
